package com.q.tqb.activity.send;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ZoomControls;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.q.tqb.R;
import com.q.tqb.activity.grab.GrabMapActivity;
import com.q.tqb.base.BaseActivity;
import com.q.tqb.util.FileUtil;
import com.q.tqb.util.LogUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SelectMapLocationActivity extends BaseActivity {


    @BindView(R.id.map_view)
    TextureMapView mMapView;
    @BindView(R.id.rb_km1)
    RadioButton mRbKm1;
    @BindView(R.id.rb_km2)
    RadioButton mRbKm2;
    @BindView(R.id.rb_km5)
    RadioButton mRbKm5;
    @BindView(R.id.rg_km)
    RadioGroup mRgKm;
    @BindView(R.id.bt_confirm)
    Button mBtConfirm;
    @BindView(R.id.iv_location)
    ImageView mIvLocation;

    private BaiduMap mBaiduMap;

    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private LatLng curLatLng;
    private LatLng startLatLng;
    private int curDistance;
    private Overlay myOverlay;
    private Marker marker;
    private GeoCoder mSearch;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(curLatLng));
            } else {
                mProgressDialog.dismiss();
            }
        }
    };

    @Override
    public int getLayoutId() {
        return R.layout.activity_select_map_location;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        curDistance = 0;
        setTitle("选择红包位置");
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMyLocationEnabled(true);
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(listener);

        View child = mMapView.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.INVISIBLE);
        }

        // 不显示地图上比例尺
        mMapView.showScaleControl(false);

        //不显示地图缩放控件（按钮控制栏）
        // mMapView.showZoomControls(false);

        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(myListener);
        initLocation();
        mRgKm.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                switch (i) {
                    case R.id.rb_km1:
                        curDistance = 1000;
                        addMark();
                        break;
                    case R.id.rb_km2:
                        curDistance = 2000;
                        addMark();
                        break;
                    case R.id.rb_km5:
                        curDistance = 5000;
                        addMark();
                        break;
                    default:
                        break;
                }
            }
        });

    }


    @OnClick({R.id.iv_back, R.id.bt_confirm, R.id.iv_location})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.bt_confirm:
                confirmLocation();
                break;
            case R.id.iv_location:
                mBaiduMap.setMyLocationEnabled(true);
                mLocationClient.start();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSearch.destroy();
    }

    private void confirmLocation() {
        mProgressDialog.show();
        mBaiduMap.snapshot(new BaiduMap.SnapshotReadyCallback() {
            @Override
            public void onSnapshotReady(final Bitmap bitmap) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        File file = FileUtil.createFile("map.png");
                        FileOutputStream out;
                        try {
                            out = new FileOutputStream(file);
                            if (bitmap.compress(Bitmap.CompressFormat.PNG, 30, out)) {
                                out.flush();
                                out.close();
                            }
                            // showToast("屏幕截图成功，图片存在: " + file.toString());
                            mHandler.sendEmptyMessage(0);
                        } catch (IOException e) {
                            e.printStackTrace();
                            mHandler.sendEmptyMessage(1);
                        }
                    }
                }).start();

            }
        });
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        //可选，设置发起定位请求的间隔，int类型，单位ms
        option.setScanSpan(0);
        option.setOpenGps(true);
        option.setLocationNotify(true);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)
        option.setIgnoreKillProcess(false);
        option.setWifiCacheTimeOut(5 * 60 * 1000);
        mLocationClient.setLocOption(option);
        mLocationClient.start();


        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {
                startLatLng = mapStatus.target;
            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {

                curLatLng = mapStatus.target;
                if (startLatLng.longitude != curLatLng.longitude || startLatLng.latitude != curLatLng.latitude) {
                    addMark();
                }
            }
        });
    }

    private class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            float radius = location.getRadius();
            String coorType = location.getCoorType();
            int errorCode = location.getLocType();


            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
            curLatLng = latLng;

            LogUtil.i(latLng.toString());

            if (curDistance == 5000) {
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(curLatLng, 13f);
                mBaiduMap.animateMapStatus(u);
                addMark();
            } else if (curDistance == 2000) {
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(curLatLng, 14f);
                mBaiduMap.animateMapStatus(u);
                addMark();
            } else if (curDistance == 1000) {
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(curLatLng, 15f);
                mBaiduMap.animateMapStatus(u);
                addMark();
            } else if (curDistance == 0) {
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(curLatLng, 15f);
                mBaiduMap.animateMapStatus(u);
            }

        }
    }

    private void addMark() {
        if (myOverlay != null) {
            myOverlay.remove();

        }
        if (marker != null) {
            marker.remove();
        }
        OverlayOptions ooCircle = new CircleOptions()
                .center(curLatLng)
                .stroke(new Stroke(1, 0xffec4159))
                .fillColor(0x22ec4159)
                .radius(curDistance);

        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.ic_location_red);
        OverlayOptions option = new MarkerOptions()
                .position(curLatLng)
                .icon(bitmap);

        myOverlay = mBaiduMap.addOverlay(ooCircle);
        marker = (Marker) mBaiduMap.addOverlay(option);

    }

    OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {

        @Override
        public void onGetGeoCodeResult(GeoCodeResult result) {

            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                //没有检索到结果

            }

            //获取地理编码结果
        }

        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
            mProgressDialog.dismiss();
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                //没有找到检索结果
                showToast("网络不佳，请检查网络");

            } else {
                mProgressDialog.dismiss();
                String province = result.getAddressDetail().province;
                String city = result.getAddressDetail().city;
                String district = result.getAddressDetail().district;
                String address = province + "-" + city + "-" + district;
                LogUtil.i(address);
                getIntent().putExtra("address", address);
                getIntent().putExtra("curLatLng", curLatLng);
                setResult(RESULT_OK, getIntent());
                finish();
            }
        }

        //获取反向地理编码结果

    };
}
